#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
import matplotlib
matplotlib.use('cairo.pdf')
from matplotlib import pyplot
import numpy
import psycopg2

import cPickle as pickle
import glob
import sys

from util import *


def get_torrent_pop(cv_dirs, infohash):
  query = """SELECT COUNT(*) FROM
             (SELECT P.peer
              FROM peer_lists_%(suffix)s P
              WHERE P.dhtkey = digest(decode('%(infohash)s', 'hex'),'sha1')
              GROUP BY P.peer)s"""
  conn = get_db_conn()
  c = conn.cursor()
  pops = []
  for dir in cv_dirs:
    s = get_db_suffix(dir)
    full_query = query % {'suffix': s, 'infohash': infohash}
    c.execute(full_query)
    pops.append((c.fetchone()[0], s))
  return pops


def plot_torrent_pop(cv_dirs, infohash):
  cv_dirs.sort()
  data = get_torrent_pop(cv_dirs,infohash)
  print data
    
  pyplot.bar(range(len(data)), [x[0] for x in data], color='k')
  pyplot.xlabel('Day')
  pyplot.ylabel('# of IPs')
  pyplot.title('Lost Ep. 16 Popularity over time')
  pyplot.xticks([27.5, 30.5, 33.5, 36.5, 39.5, 42.5, 45.5],
                ['19', '20', '21', '22', '23', '24', '25'])

  pyplot.savefig('single_pop_plot.pdf')

  
if __name__ == '__main__':
  plot_torrent_pop(glob.glob(sys.argv[1]), sys.argv[2])
